<template>
	<view>
		<view class="blank"></view>
		<view class="classify-list">
			<view>
				<uni-badge :text="info.interaction" class="mark" style="background: #FF0844;" type="error" size="small" />
				<!-- <image class="interact" src="../../static/pages/interact.png" @click="toPage('/pages/message/hudong')"></image> -->
				<image class="interact" src="../../static/pages/interact_1.png" @click="popHouse"></image>
				<view class="text">群聊大厅</view>
			</view>
			<view class="system">
				<uni-badge :text="system" class="mark" style="background: #FF0844;" type="error" size="small" />
				<image class="interact" src="../../static/pages/system_1.png" @click="popXiton"></image>
				<view class="text">系统消息</view>
			</view>
			<view class="system">
				<uni-badge :text="interaction" class="mark" style="background: #FF0844;" type="error" size="small" />
				<image class="interact" src="../../static/pages/active1_1.png" @click="popActive"></image>
				<view class="text">活动消息</view>
			</view>
		<!-- 	<view class="system" v-if="wxLoginState==1">
				<image class="interact" src="../../static/pages/active1.png" @click="goTask"></image>
				<view class="text">任务大厅</view>
			</view> -->
		</view>
		<view class="blank1" v-if="list.length > 0">
			<view class="info-list">
				<view class="info-item d-flex-jsb" v-for="(d, index) in list" :key="index" @click="roomTim(d)">
					<view class="info-l">
						<image :src="d.avatar" mode="heightFix"></image>
					</view>
					<view class="info-r">
						<view class="info-user-name d-flex-jsb">
							<view>{{ d.nickname }}</view>
							<span class="unread-box" v-if="d.unreadCount">{{ d.unreadCount }}</span>
						</view>
						<view class="info-content d-flex-jsb" v-if="d.chatKey && !!d.chatKey.data">
							<text>{{ chatContent[d.chatKey.data] }}</text>
						</view>
						<view class="info-content d-flex-jsb" v-else>
							<text v-if="d.message">{{ d.message }}</text>
							<text v-else-if="d.chatKey && d.chatKey.text">{{d.chatKey.text}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-if="list.length === 0">
			<image class="no" src="../../static/pages/no.png"></image>
		</view>
		<voiceChatModal></voiceChatModal>
		<video-chat></video-chat>
	</view>
</template>

<script>
	import uniBadge from '@/components/uni-badge/uni-badge.vue';
	export default {
		data() {
			return {
				info: {},
				list: [],
				datas: [],
				userData: [],
				chatContent: {
					mapFile: '位置消息',
					chatFile: '图片信息',
					voiceFile: '语音信息',
					videoFile: '视频信息',
					redEnvelopeData: '[红包]',
					voiceChat: '邀请您进行语音聊天',
					voiceChatCancel: '拒绝了音频通话',
					voiceChatSelfCancel: '挂断了音频通话'
				},
				isShowUnreadTips: false,
				system:0,
				interaction:0,
				wxLoginState:2,//微信登录显示隐藏
			};
		},
		watch: {
			isShowUnreadTips(newVal, oldVal) {
				if (newVal) {
					uni.setTabBarItem({
						index: 2,
						iconPath: "/static/img/message_1_unread.png",
						selectedIconPath: "/static/img/message-show_1_unread.png"
					})
				}
			}
		},
		components: {
			uniBadge,
		},
		onShow() {
			this.getWxLoginState();
			let userInfo = JSON.parse(uni.getStorageSync('userInfo'));
			this.getUserSig(userInfo.id);
			setTimeout(res => {
				this.getData();
			}, 300);
			uni.setTabBarItem({
				index: 2,
				iconPath: "/static/img/message_1.png",
				selectedIconPath: "/static/img/message-show_1.png",
			})
			this.getMessage()
		},
		mounted() {
			let that = this;
			let onMessageReceived = function(event) {
				let num = 1;
				let index = 0;
				let number = 1;
				for (let i = 0; i < event.data.length; i++) {
					if (event.data[i].conversationType === 'GROUP') return
					for (let a = 0; a < that.list.length; a++) {
						index = that.list[a].num;
						if (event.data[i].conversationID == that.list[a].conversationID) {
							index++;
							number = a;
						}
					}
					if (index == 0) {
						that.$utils.postrequest("/api/getuser", {
							user_id: event.data[i].from
						}, function(res) {
							if (res.code == 200) {
								if (event.data[i].type == "TIMTextElem") {
									var newDate = new Date();
									newDate.setTime(event.data[i].time * 1000);
									let objs = {
										conversationID: event.data[i].conversationID,
										avatar: res.data.avatar,
										nickname: res.data.nickname,
										userId: event.data[i].from,
										time: newDate.toLocaleTimeString(),
										message: event.data[i].payload.text,
										num: 1,
										user: res.data,
										chatKey: res.data.chatKey
									};
									that.merge(objs)
								}
								index = 0;
							}
						})
					} else if (index > 0) {
						var newDate = new Date();
						newDate.setTime(event.data[i].time * 1000);
						let arr = that.list;
						for (let a = 0; a < arr.length; a++) {
							arr[number].num = index;
							arr[number].message = event.data[i].payload.text;
							arr[number].time = newDate.toLocaleTimeString();
						}
						that.list = [...arr];
					}
					number = 0;
					// if(event.data[i]&&event.data[i].conversationID){}
				}
				// 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
				// event.name - TIM.EVENT.MESSAGE_RECEIVED
				// event.data - 存储 Message 对象的数组 - [Message]
			};
			let onSDKNoReady = function(event) {

				// // console.log('-------sdk----no');
			};
			this.tim.on(this.$TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
			this.tim.on(this.$TIM.EVENT.SDK_NOT_READY, onSDKNoReady);
		},

		methods: {
			getWxLoginState() {
				this.$utils.request('/api/config/switch', {id:1}, res => {
					if (res.code == 200) {
						this.wxLoginState = res.data.config_status;
					}
				})
			},
			goTask(){
				uni.showToast({
					icon:'none',
					title:"暂未开放"
				})
				// uni.navigateTo({
				// 	url:'/pages/active/task'
				// })
			},
			// 获取系统消息
			getMessage() {
				let that = this
				this.$utils.request('/api/message/index', {}, function(res) {
					if (res.code == 200) {
						let {
							data: {
								system,
								interaction
							}
						} = res
						that.system = system
						that.interaction = interaction
						// console.log(system)
						// console.log(interaction)
					} else {
						that.$utils.showLayer(res.message);
					}
				});
			},
			//判断有没有重复数据
			merge(obj) {
				uni.setTabBarItem({
					index: 2,
					iconPath: "/static/img/message_1_unread.png",
					selectedIconPath: "/static/img/message-show_1_unread.jpeg"
				})
				let bol = true
				this.list.forEach((item, index) => {
					if (item.conversationID == obj.conversationID) {
						item = Object.assign(item, obj)
						bol = false
						item.unreadCount = item.unreadCount ? item.unreadCount + 1 : 1
						// console.log(item.unreadCount)
						const targetRow = this.list.splice(index, 1)[0]
						this.list.splice(0, 0, targetRow)
						// const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
						// this.newList.splice(evt.newIndex, 0, tempIndex)
					}
				})
				if (bol) {
					obj.unreadCount = 1
					this.list.unshift(obj)
				}
			},
			getUserSig(userId) {
				let that = this;
				this.$utils.postrequest('/api/timuser/index?userid=' + userId, {
					userid: userId
				}, function(res) {
					if (res.code == 200) {
						// // console.log("用户ID:" + userId);
						//根据返回的userID 以及 userSig 登录tim
						let promise = that.tim.login({
							userID: userId.toString(),
							userSig: res.data
						});
						promise
							.then(resData => {
								//登录成功后 更新登录状态
								that.$store.commit('toggleIsLogin', true);
								//自己平台的用户基础信息
								//tim 返回的用户信息
								uni.setStorageSync('userTIMInfo', JSON.stringify(resData.data));
								// console.log("登录成功！！！！");
							})
							.catch(err => {
								console.warn('login error:', err); // 登录失败的相关信息
							});

					} else {
						that.$utils.showLayer(res.message);
					}
				});
			},
			roomTim(data) {
				let that = this;
				if (data.conversationID.indexOf("GROUP") > -1) {
					let GroupId = data.conversationID.substr(5, data.conversationID.length - 1)
					that.$store.commit('createConversationActive', {
						type: "group",
						data: GroupId
					})
					uni.setStorageSync('titleText', data.nickname);
					uni.setStorageSync('chooseGroup', GroupId);
					uni.navigateTo({
						url: '/pages/tim/group'
					})
				} else {
					let userId = data.user.userID || data.user.id;
					this.$store.commit('createConversationActive', {
						type: "C2C",
						data: userId
					})
					uni.setStorageSync('chooseUser', data.user);
					uni.navigateTo({
						url: '/pages/tim/room'
					})
				}
			},
			getData() {
				let that = this;
				that.userData = [];
				// 拉取会话列表
				let promise = this.tim.getConversationList();
				if (!!promise) {
					promise.then((imResponse) => {
						// console.log(imResponse)
						const conversationList = imResponse.data.conversationList;
						conversationList.forEach((e, i) => {
							var newDate = new Date();
							newDate.setTime(conversationList[i].lastMessage.lastTime * 1000);
							if (e.type === "C2C") {
								if (!e.userProfile.avatar) {
									this.$utils.postrequest("/api/getuser", {
										user_id: e.userProfile.userID
									}, function(res) {
										if (res.code == 200) {
											e.userProfile.avatar = res.data.avatar
											e.userProfile.nick = res.data.nickname
											let objs = {
												type: e.type,
												conversationID: e.conversationID,
												avatar: e.userProfile.avatar,
												nickname: e.userProfile.nick,
												userId: e.lastMessage.fromAccount,
												id: e.lastMessage.fromAccount,
												time: newDate.toLocaleTimeString(),
												message: e.lastMessage.messageForShow,
												num: 0,
												user: e.userProfile,
												chatKey: e.lastMessage.payload,
												unreadCount: e.unreadCount,
												sort: i
											};
											if (e.unreadCount > 0 && !that.isShowUnreadTips) that.isShowUnreadTips = true
											that.userData.push(objs)
											that.list = that.userData
										}
									})
								} else {
									let objs = {
										type: e.type,
										conversationID: e.conversationID,
										avatar: e.userProfile.avatar,
										nickname: e.userProfile.nick,
										userId: e.lastMessage.fromAccount,
										id: e.lastMessage.fromAccount,
										time: newDate.toLocaleTimeString(),
										message: e.lastMessage.messageForShow,
										num: 0,
										user: e.userProfile,
										chatKey: e.lastMessage.payload,
										unreadCount: e.unreadCount,
										sort: i
									}
									// console.log(e.unreadCount)
									if (e.unreadCount > 0 && !that.isShowUnreadTips) that.isShowUnreadTips = true
									this.userData.push(objs)
									this.list = this.userData
								}

								this.list = this.list.sort((a, b) => a.sort - b.sort)
								let obj = {}
								this.list = this.list.reduce((cur, next) => {
									obj[next.user.userID] ? "" : obj[next.user.userID] = true && cur.push(next);
									return cur;
								}, []) //设置cur默认类型为数组，并且初始值为空的数组
								// 	if (!e.userProfile.avatar) {
								// 		that.$utils.postrequest("/api/getuser", {
								// 			user_id: e.userProfile.userID
								// 		}, function(res) {
								// 			if (res.code == 200) {
								// 				e.userProfile.avatar = res.data.avatar
								// 				e.userProfile.nick = res.data.nickname
								// 				let objs = {
								// 					type:e.type,
								// 					conversationID: e.conversationID,
								// 					avatar: e.userProfile.avatar,
								// 					nickname: e.userProfile.nick,
								// 					userId: e.lastMessage.fromAccount,
								// 					id: e.lastMessage.fromAccount,
								// 					time: newDate.toLocaleTimeString(),
								// 					message: e.lastMessage.messageForShow,
								// 					num: 0,
								// 					user: e.userProfile,
								// 					chatKey: e.lastMessage.payload,
								// 					unreadCount: e.unreadCount,
								// 					sort: i
								// 				};
								// 				that.userData.push(objs)
								// 				that.list = that.userData
								// 				that.list = that.list.sort((a, b) => a.sort - b.sort)
								// 				let obj = {}
								// 				that.list = that.list.reduce((cur,next) => {
								// 				    obj[next.user.userID] ? "" : obj[next.user.userID] = true && cur.push(next);
								// 				    return cur;
								// 				},[]) //设置cur默认类型为数组，并且初始值为空的数组
								// 			}
								// 		})
								// 	} else {
								// 		if (e.lastMessage.payload.text) {
								// 			// console.log(e.lastMessage.payload.text)
								// 		}
								// 		let objs = {
								// 			conversationID: e.conversationID,
								// 			avatar: e.userProfile.avatar,
								// 			nickname: e.userProfile.nick,
								// 			userId: e.lastMessage.fromAccount,
								// 			id: e.lastMessage.fromAccount,
								// 			time: newDate.toLocaleTimeString(),
								// 			message: e.lastMessage.messageForShow,
								// 			num: 0,
								// 			user: e.userProfile,
								// 			chatKey: e.lastMessage.payload,
								// 			unreadCount: e.unreadCount,
								// 			sort: i
								// 		}
								// 		that.userData.push(objs)
								// 		that.list = that.userData
								// 		that.list = that.list.sort((a, b) => a.sort - b.sort)
								// 		let obj = {}
								// 		that.list = that.list.reduce((cur,next) => {
								// 		    obj[next.user.userID] ? "" : obj[next.user.userID] = true && cur.push(next);
								// 		    return cur;
								// 		},[]) //设置cur默认类型为数组，并且初始值为空的数组
								// 	}
							}
						})
					}).catch(function(imError) {
						console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
					});
				}
			},
			getUserInfo(e, newDate) {

			},
			toPage(url) {
				uni.navigateTo({
					url
				});
			},
			pop() {
				uni.showToast({
					title: '暂无最新消息',
					icon: 'none'
				});
			},
			popActive() {
				uni.navigateTo({
					url: './popActive'
				});
			},
			popXiton() {
				uni.navigateTo({
					url: './xiton'
				});
			},
			popHouse() {
				uni.navigateTo({
					url: './house'
				});
			}
		}
	};
</script>

<style>
	.unread-box {
		height: 30rpx;
		width: 30rpx;
		border-radius: 50%;
		background-color: red;
		color: #FFFFFF;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24rpx;
	}

	.blank {
		width: 100%;
		height: 3px;
		background: #e0e0e0;
	}

	.classify-list {
		display: flex;
		/* flex-wrap: wrap; */
		align-items: center;
		justify-content: space-around;
		padding-top: 24rpx;
		/* margin: 24rpx 0rpx 0rpx 76rpx; */
	}

	.interact {
		width: 88rpx;
		height: 88rpx;
	}

	.text {
		font-size: 24rpx;
		font-family: PingFang SC;

		color: #282635;
		line-height: 43rpx;
	}

	.system {
		/* margin-left: 163rpx; */
	}

	.blank1 {
		width: 689rpx;
		height: 10rpx;
		background: #f6f5fa;
		margin: 28rpx 0rpx 0rpx 30rpx;
	}

	.no {
		width: 281rpx;
		height: 281rpx;
		margin: 133rpx 0rpx 0rpx 240rpx;
	}

	.mate {
		width: 270rpx;
		height: 94rpx;
		margin: 350rpx 0rpx 0rpx 480rpx;
	}

	.mark {
		position: absolute;
		margin-left: 58rpx;
		/* width: 33rpx; */
		/* height: 40rpx; */
		z-index: 1;
	}

	.d-flex-jsb {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.info-item {
		padding: 30rpx 0;
		border-bottom: 1px solid #eee;
	}

	.info-l {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		overflow: hidden;
		background: #eee;
		display: flex;
		align-items: center;
	}

	.info-r {
		width: calc(100% - 120rpx);
	}

	.info-l image {
		width: 100%;
		height: 100%;
	}

	.info-content text,
	.info-user-name text {
		color: #999;
		font-size: 25rpx;
	}

	.info-content {
		margin-top: 10rpx;
	}

	.info-content view {
		width: 33rpx;
		height: 33rpx;
		text-align: center;
		line-height: 33rpx;
		font-size: 24rpx;
		color: #fff;
		background: #ff6049;
		border-radius: 50%;
	}
</style>
